package com.proton.carepatchtemp.fragment;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.activity.MainActivity;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Config;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.constant.NtfID;
import com.proton.carepatchtemp.constant.XTypes;
import com.proton.carepatchtemp.database.XmppMsg;
import com.proton.carepatchtemp.fragment.dialogfragment.TestNoticeFragment;
import com.proton.carepatchtemp.utils.FormatUtils;
import com.proton.carepatchtemp.utils.Ntf.NotificationUtils;
import com.proton.carepatchtemp.utils.NumUtils;
import com.proton.carepatchtemp.utils.SpUtils;
import com.proton.carepatchtemp.utils.ThreadUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.XMPPCenter;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;

import cn.qqtheme.framework.picker.NumberPicker;

import static android.content.Context.NOTIFICATION_SERVICE;
import static com.proton.carepatchtemp.constant.Config.WARNING_DIV_DEFAULT;
import static com.proton.carepatchtemp.constant.NtfID.LOW_OR_HIGH_WARNING;


public class RealTimeShareFragment extends RealTimeItemFragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    public String reportID;
    private boolean isInit = false;
    private Typeface mFace;
    private long from = 0;
    //  数据接收超时
    private long recTimeout = 0;

    private String displayName = "";
    private XmppMsg mParam2;
    private ImageView mIvDelete;
    private SimpleDraweeView mSdvProfileAvatar;
    /**
     * ---
     */
    private TextView mTvProfileName;
    /**
     * --.--
     */
    private TextView mTvRealTimeTemp;
    /**
     * ℃
     */
    private TextView mTvTempUnit;
    private RelativeLayout mRtlRealTimeTemp;
    /**
     * --.--
     */
    private TextView mTvRealtimeHighestTemp;
    /**
     * ℃
     */
    private TextView mTvTempUnit1;
    /**
     * --时--分
     */
    private TextView mTvSumTestTime;
    /**
     * --.-℃
     */
    private TextView mTvSettingWarningLow;
    /**
     * --.-℃
     */
    private TextView mTvSettingWarningHigh;


    //  温度单位标志 1 = 摄氏度； 2 = 华氏度

    private int unit = 0;

    private float displayCurrent = 0f;

    private NumberPicker mHighTempPicker;
    private NumberPicker mLowTempPicker;
    private boolean CanHighNtf = true;
    private boolean CanLowNtf = false;
    private LinearLayout mLnlRangeNotice;
    private ImageView mIvShowNotice;

    public RealTimeShareFragment() {
    }

    public static RealTimeShareFragment newInstance(String reportId, XmppMsg param2, String param3) {
        RealTimeShareFragment fragment = new RealTimeShareFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, reportId);
        args.putSerializable(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        this.isShare = true;
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            reportID = getArguments().getString(ARG_PARAM1);
            mParam2 = (XmppMsg) getArguments().getSerializable(ARG_PARAM2);
        }
        unit = SpUtils.getInt(Extras.TEMP_UNIT, Config.TEMP_UNIT_DEFAULT);
        mFormat = new DecimalFormat("###,###,###,###.00");
        mFace = Typeface.createFromAsset(getActivity().getAssets(), "fonts/DIGITAL-7MONO.TTF");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_real_time_share, container, false);
        initView(view);
        setListener();

        if (1 == unit) {
            mTvTempUnit.setText("℃");
            mTvTempUnit1.setText("℃");
        } else if (2 == unit) {
            mTvTempUnit.setText("℉");
            mTvTempUnit1.setText("℉");
        }

        if (0 == displayCurrent) {
            new ShareUpdataTempTimer(Long.MAX_VALUE, 1000).start();
        }

        isInit = true;

        updataUI(mParam2);
        return view;
    }

    private void setListener() {

        mIvShowNotice.setOnClickListener(v -> {
            TestNoticeFragment testNoticeFragment = TestNoticeFragment.newInstance(null, null);
            testNoticeFragment.show(getChildFragmentManager(), "testNoticeFragment");
        });

        mIvDelete.setOnClickListener(v -> {

            AlertDialog.Builder ADBuilder = new AlertDialog.Builder(getActivity());
            ADBuilder.setTitle(R.string.string_tips);
            ADBuilder.setMessage(R.string.string_stop_get_data);
            ADBuilder.setNegativeButton(getString(R.string.string_cancel), (dialog, which) -> {

            });
            ADBuilder.setNeutralButton(getString(R.string.string_confirm), (dialog, which) -> {
                XmppMsg xmppMsg = new XmppMsg();
                xmppMsg.setReportId(Long.parseLong(reportID));
                xmppMsg.setDisplayStatus(XTypes.STATUS_DELETEPAGER);
                EventBus.getDefault().post(new MainEvent(xmppMsg.getReportId() + "", Codes.XMPP_MSG_DATA, xmppMsg));
                XmppMsg xmppMsg2 = new XmppMsg();
                xmppMsg2.setReportId(Long.parseLong(reportID));
                xmppMsg2.setDisplayStatus(XTypes.STATUS_STOPREC);
                XMPPCenter.sendMsg(xmppMsg2, from);
            });
            AlertDialog dialog = ADBuilder.create();
            dialog.setCancelable(false);
            //在dialog  show方法之前添加如下代码，表示该dialog是一个系统的dialog**
            dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_TOAST));
            dialog.show();

        });

        mTvSettingWarningLow.setOnClickListener(view -> {
            initPicker();
            mLowTempPicker.show();
        });

        mTvSettingWarningHigh.setOnClickListener(view -> {
            initPicker();
            mHighTempPicker.show();
        });

    }

    private void initPicker() {
        if (1 == unit) {
            mHighTempPicker = new NumberPicker(getActivity());
            mHighTempPicker.setRange(37.0, 42.9, 0.1);
            mHighTempPicker.setSelectedItem(FormatUtils.float2double(highWarning));
            mHighTempPicker.setLabel("℃");
            mHighTempPicker.setTitleText(R.string.config_height_temp);

            mLowTempPicker = new NumberPicker(getActivity());
            mLowTempPicker.setRange(30.0, 35.9, 0.1);
            mLowTempPicker.setSelectedItem(FormatUtils.float2double(lowWarning));
            mLowTempPicker.setLabel("℃");
            mLowTempPicker.setTitleText(R.string.config_low_temp);
        } else if (2 == unit) {
            mHighTempPicker = new NumberPicker(getActivity());
            mHighTempPicker.setRange(98.6, 109.2, 0.1);
            mHighTempPicker.setSelectedItem(FormatUtils.float2double(FormatUtils.c2F(highWarning)));
            mHighTempPicker.setLabel("℉");
            mHighTempPicker.setTitleText(R.string.config_height_temp);

            mLowTempPicker = new NumberPicker(getActivity());
            mLowTempPicker.setRange(86.0, 96.6, 0.1);
            mLowTempPicker.setSelectedItem(FormatUtils.float2double(FormatUtils.c2F(lowWarning)));
            mLowTempPicker.setLabel("℉");
            mLowTempPicker.setTitleText(R.string.config_low_temp);

        }

        mLowTempPicker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() {
            @Override
            public void onNumberPicked(int index, Number item) {
                if (1 == unit) {
                    lowWarning = item.floatValue();
                    mTvSettingWarningLow.setText(item.floatValue() + "℃");

                } else if (2 == unit) {
                    lowWarning = FormatUtils.f2C(item.floatValue());
                    mTvSettingWarningLow.setText(item.floatValue() + "℉");
                }
            }
        });


        mHighTempPicker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() {
            @Override
            public void onNumberPicked(int index, Number item) {
                if (1 == unit) {
                    highWarning = item.floatValue();
                    mTvSettingWarningHigh.setText(item.floatValue() + "℃");
                } else if (2 == unit) {
                    highWarning = FormatUtils.f2C(item.floatValue());
                    mTvSettingWarningHigh.setText(item.floatValue() + "℉");
                }
            }
        });
    }

    @Override
    public void dealEvent(MainEvent event) {

        switch (event.getId()) {
            case Codes.SETTING_TEMP_UNIT_C:
                unit = 1;
                mTvTempUnit.setText("℃");
                mTvTempUnit1.setText("℃");
                break;
            case Codes.SETTING_TEMP_UNIT_F:
                unit = 2;
                mTvTempUnit.setText("℉");
                mTvTempUnit1.setText("℉");
                break;
            default:
                break;
        }

    }

    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }

    public void addData(XmppMsg xmppMsg, long from) {

        this.from = from;
        displayCurrent = xmppMsg.getDisplayCurrent();
        LogUtils.d("displayCurrent = " + displayCurrent);
        displayName = xmppMsg.getDisplayName();
        recTimeout = 0;

        if (isInit) {
            updataUI(xmppMsg);
        }

    }


    private void updataUI(XmppMsg xmppMsg) {
        mSdvProfileAvatar.setImageURI(xmppMsg.displayAvatar);
        mTvProfileName.setText(xmppMsg.getDisplayName());
        String[] now = FormatUtils.transferLongToDate("yyyy/MM/dd HH:mm:ss", xmppMsg.getNow()).split(" ");
        mTvSumTestTime.setText(now[1]);

        //更新最高温度和实时温度
        if (1 == unit) {
            mTvRealtimeHighestTemp.setText(mFormat.format(xmppMsg.getDisplayMax()));
            //不在有效范围内不显示
            if (NumUtils.withinTempRange(displayCurrent)) {
                mTvRealTimeTemp.setText(mFormat.format((double) displayCurrent));
                mLnlRangeNotice.setVisibility(View.INVISIBLE);
            } else {
                mTvRealTimeTemp.setText("--.--");
                mLnlRangeNotice.setVisibility(View.VISIBLE);
            }
        } else if (2 == unit) {
            mTvRealtimeHighestTemp.setText(mFormat.format(FormatUtils.c2F(xmppMsg.getDisplayMax())));
            //不在有效范围内不显示
            if (NumUtils.withinTempRange(displayCurrent)) {
                mTvRealTimeTemp.setText(mFormat.format((double) FormatUtils.c2F(displayCurrent)));
                mLnlRangeNotice.setVisibility(View.INVISIBLE);
            } else {
                mTvRealTimeTemp.setText("--.--");
                mLnlRangeNotice.setVisibility(View.VISIBLE);
            }
        }

    }

    private void initView(View view) {
        mIvDelete = view.findViewById(R.id.iv_delete);
        mSdvProfileAvatar = view.findViewById(R.id.sdv_profile_avatar);
        mTvProfileName = view.findViewById(R.id.tv_profile_name);
        mTvRealTimeTemp = view.findViewById(R.id.tv_real_time_temp);
        mTvTempUnit = view.findViewById(R.id.tv_temp_unit);
        mRtlRealTimeTemp = view.findViewById(R.id.rtl_real_time_temp);
        mTvRealtimeHighestTemp = view.findViewById(R.id.tv_realtime_highest_temp);
        mTvTempUnit1 = view.findViewById(R.id.tv_temp_unit1);
        mTvSumTestTime = view.findViewById(R.id.tv_sum_test_time);
        mTvSettingWarningLow = view.findViewById(R.id.tv_setting_warning_low);
        mTvSettingWarningHigh = view.findViewById(R.id.tv_setting_warning_high);
        mLnlRangeNotice = view.findViewById(R.id.lnl_range_notice);
        mIvShowNotice = view.findViewById(R.id.iv_show_notice);
        mTvRealTimeTemp.setTypeface(mFace);
    }

    /**
     * @param type 1高烧 2低烧
     */
    private void showNotification(int type) {

        try {
            if (null == getActivity() || getActivity().isDestroyed()) {
                return;
            }
            Intent intent = new Intent(getActivity(), MainActivity.class);
            if (type == 1) {
                NotificationUtils.createNotif(getActivity(), VCare.get().getString(R.string.child_have_fever),
                        VCare.get().getString(R.string.hava_height_fever),
                        VCare.get().getString(R.string.temp_too_height),
                        intent, NtfID.LOW_OR_HIGH_WARNING);

            } else {
                NotificationUtils.createNotif(getActivity(), VCare.get().getString(R.string.child_have_low_fever),
                        VCare.get().getString(R.string.heave_low_fever),
                        VCare.get().getString(R.string.temp_too_low),
                        intent, NtfID.LOW_OR_HIGH_WARNING);

            }
            AlertDialog.Builder ADBuilder = new AlertDialog.Builder(getActivity());
            long warningDiv = SpUtils.getLong(Extras.WARNING_TIME_DIV, WARNING_DIV_DEFAULT);
            if (1 == type) {
                ADBuilder.setTitle(R.string.high_temp_notice);

                TextView msg = new TextView(getContext());
                msg.setPadding(10, 10, 10, 10);
                msg.setGravity(Gravity.CENTER);
                msg.setText(displayName + VCare.get().getString(R.string.temp_to_height));

                ADBuilder.setView(msg);
            } else {
                ADBuilder.setTitle(R.string.low_temp_notice);

                TextView msg = new TextView(getContext());
                msg.setPadding(10, 10, 10, 10);
                msg.setGravity(Gravity.CENTER);
                msg.setText(displayName + VCare.get().getString(R.string.temp_is_too_low));

                ADBuilder.setView(msg);
            }

            ADBuilder.setNegativeButton(R.string.never_notice, (dialog, which) -> {
                clearNotification(NtfID.LOW_OR_HIGH_WARNING);
                if (1 == type) {
                    CanHighNtf = false;
                } else {
                    CanLowNtf = false;
                }
            });

            ADBuilder.setPositiveButton(FormatUtils.formatTime(warningDiv) + "  " + getString(R.string.butixiang), (dialog, which) -> {
                clearNotification(LOW_OR_HIGH_WARNING);
                Runnable runnable = () -> {

                    int tp = type;

                    if (1 == tp) {
                        for (int i = 0; i <= warningDiv / 1000 && !CanHighNtf; i++) {
                            SystemClock.sleep(1000);
                        }
                        CanHighNtf = true;
                    } else {
                        for (int i = 0; i <= warningDiv / 1000 && !CanLowNtf; i++) {
                            SystemClock.sleep(1000);
                        }
                        CanLowNtf = true;
                    }

                };
                ThreadUtils.runOnOtherThread(runnable);
            });
            final AlertDialog dialog = ADBuilder.create();
            dialog.setCancelable(false);
            //在dialog  show方法之前添加如下代码，表示该dialog是一个系统的dialog**
            dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_TOAST));
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //删除通知
    private void clearNotification(int ntfCode) {
// 启动后删除之前我们定义的通知
        NotificationManager notificationManager = (NotificationManager)
                VCare.get().getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancel(ntfCode);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private class ShareUpdataTempTimer extends CountDownTimer {
        boolean isFirstHigh = true;

        public ShareUpdataTempTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long l) {
            recTimeout += 1000;
            //获取数据异常
            if (recTimeout >= 2 * 60 * 1000) {
                if (null != getActivity()) {
                    XmppMsg xmppMsg = new XmppMsg();
                    xmppMsg.setDisplayName(displayName);
                    xmppMsg.setReportId(Long.parseLong(reportID));
                    xmppMsg.setDisplayStatus(XTypes.STATIS_DELETE_NODATA);
                    EventBus.getDefault().post(new MainEvent(xmppMsg.getReportId() + "", Codes.XMPP_MSG_DATA, xmppMsg));
                }
            }

            if (isFirstHigh && displayCurrent > 36.0) {
                isFirstHigh = false;
                CanLowNtf = true;
                LogUtils.d("First time higher 36.0");
            }

            if (!isFirstHigh && displayCurrent > highWarning) {
                mRtlRealTimeTemp.setBackground(ContextCompat.getDrawable(VCare.get(), R.drawable.realtime_temp_bg_red));
                if (CanHighNtf) {
                    showNotification(1);
                    CanHighNtf = false;
                    LogUtils.d("Temp high");
                    //温度由低变高之后，需要再次开启低温提醒
                    if (!CanLowNtf)
                        CanLowNtf = true;
                }
            } else if (!isFirstHigh && displayCurrent < lowWarning) {
                mRtlRealTimeTemp.setBackground(ContextCompat.getDrawable(VCare.get(), R.drawable.realtime_temp_bg_blue_low));
                if (CanLowNtf) {
                    showNotification(2);
                    CanLowNtf = false;
                    LogUtils.d("Temp low");
                    //温度由高变低之后，需要再次开启高温提醒
                    if (!CanHighNtf)
                        CanHighNtf = true;
                }
            } else {
                mRtlRealTimeTemp.setBackground(ContextCompat.getDrawable(VCare.get(), R.drawable.realtime_temp_bg_blue));
            }

            if (1 == unit) {
                mTvSettingWarningHigh.setText(mFormat.format(highWarning) + "℃");
                mTvSettingWarningLow.setText(mFormat.format(lowWarning) + "℃");
            } else if (2 == unit) {
                mTvSettingWarningHigh.setText(mFormat.format(FormatUtils.c2FHalfDown(highWarning)) + "℉");
                mTvSettingWarningLow.setText(mFormat.format(FormatUtils.c2FHalfDown(lowWarning)) + "℉");
            }

        }

        @Override
        public void onFinish() {
            this.start();
        }
    }

}
